#!/bin/bash

#=======================================================================
# ssht
# File ID: 307e8876-e099-11e0-94c2-ef2688b28a12
# [Description]
# License: GNU General Public License version 2 or later.
#=======================================================================

progname=ssht

msg() {
    echo $progname: "$*"
}

PORT=9141
HOST=sunny@sunbase.org
CMD="ssh -A -Y -q -N -R $PORT:localhost:22 $HOST"

unset PID
PID=$(pgrep -f -x "$CMD")

if test "$1" = "-c"; then
    USERNAME=$2
    test -z "$2" && USERNAME=sunny
    sess -t c_ssht.c -- ssh -A -Y -p $PORT -l $USERNAME localhost
elif test "$1" = "-k"; then
    test -n "$PID" || { echo $progname: No tunnel found >&2; exit 1; }
    kill $PID
elif test "$1" = "-l"; then
    test -n "$PID" && echo $PID
elif test "$1" = "-t"; then
    test -n "$PID" && { echo $progname: Tunnel already active at PID $PID >&2; exit 1; }
    sess -t c_ssht.t -- $CMD &
elif test "$1" = "-v"; then
    msg Running pkill...
    pkill -9 -f "ssh -L 590$2:localhost:590$2"
    msg Creating ssh tunnel...
    sess -d ssh_tunnel -- ssh -L 590$2:localhost:590$2 -C -N -f $HOST
    quality_str=
    if test -n "$3"; then
        quality_str="-quality $3"
        msg Starting xtightvncviewer with quality $3...
        sess -- xtightvncviewer -encodings tight -depth 16 -compresslevel 9 -nocursorshape $quality_str localhost:$2
    else
        msg Starting xtightvncviewer with top quality...
        sess -- xtightvncviewer -encodings tight -truecolour -nojpeg -nocursorshape localhost:$2
    fi
    msg Destroying ssh tunnel...
    pkill -9 -f "ssh -L 590$2:localhost:590$2"
else
    echo Syntax: $progname \[ -c \| -k \| -l \| -t \| -v \]
fi
